<template>
  <div class="box">
    <div class="dialog-footer">
      <el-button @click="closeHandler">关闭</el-button>
      <el-button type="success" @click="confirmStorage"> 确认保存 </el-button>
    </div>
    <div class="dialog-view">
      <div class="dialog-view-item" style="width: 65%">
        <div class="storage-box">
          <el-form :model="query" :inline="true" ref="ruleFormRef">
            <el-form-item label="库位代号" prop="warehousecode">
              <el-input v-model="query.warehousecode" name="warehousecode" clearable />
            </el-form-item>

            <el-form-item label="库位名称" prop="repositoryname">
              <el-input v-model="query.repositoryname" name="repositoryname" clearable />
            </el-form-item>

            <!-- <el-form-item label="所属仓库编码" prop="owning_id">
              <el-input v-model="query.owning_id" name="owning_id" clearable />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">查询</el-button>
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
              <!-- <el-button type="primary" @click="submitForm(form)">{{ $t('system.confirm') }}</el-button> -->
            </el-form-item>
          </el-form>

          <div class="table-default">
            <el-table
              :data="tableData"
              class="mt-3"
              v-loading="loading"
              @selection-change="handleSelectionChange"
              @select="selectHandler"
              @getSelectionRows="handlegetSelectionRows"
              @select-all="selectAllHandler"
              border
              ref="tableRef"
            >
              <el-table-column type="selection" />
              <el-table-column prop="id" label="行号" width="60" />
              <el-table-column prop="owning_id" label="所属仓库名称" />
              <el-table-column prop="warehousecode" label="库位代号" />
              <el-table-column prop="repositoryname" label="库位名称" />
            </el-table>
            <Paginate />
          </div>
        </div>
      </div>
      <div class="dialog-view-item" style="width: 30%">
        <!-- 保存数组saveArr-- {{ saveArr }}
        <hr>
        选中数组selectArr-- {{ selectArr }} -->

        <el-table :data="tableRightData" border>
          <el-table-column prop="id" label="行号" />
          <el-table-column prop="warehousecode" label="仓库代码" />
          <el-table-column #default="scope" label="删除">
            <el-button type="danger" size="small" :icon="Delete" circle @click="deleteHandler(scope.row)" />
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, reactive, watch, onUpdated } from 'vue'

import { useGetList } from '/admin/composables/curd/useGetList'
import { useDestroy } from '/admin/composables/curd/useDestroy'
import { useOpen } from '/admin/composables/curd/useOpen'
import http from '/admin/support/http'
import { Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
const api = 'warehouse/storage'
let tableData = ref([])
let tableRightData = ref([])
let selectArr = ref([])

console.log('触发')

const loading = ref(false)

const props = defineProps({
  wmsCode: String,
})

// let wmsCode = ref(props.wmsCode)

// console.log(wmsCode.value)

// watch(props.wmsCode,(newValue,oldValue)=>{
//   console.log("新值是"+newValue, "旧址是"+oldValue);
// })
// watch(wmsCode,(newValue,oldValue)=>{
//   console.log("新值是"+newValue, "旧址是"+oldValue);
// })

let query = reactive({
  warehousecode: '',
  repositoryname: '',
  fnumber: props.wmsCode,
  limit: 100,
})
let tableRef = ref(null)
let ruleFormRef = ref(null)

const submitForm = () => {
  saveHandler()
  console.log(selectArr.value)
  console.log(query)
  getSotrageList(query)
}

const resetForm = () => {
  saveHandler()
  ruleFormRef.value.resetFields()
  getSotrageList(query)
}

// 存起来的数组 saveArr
// 选中的数组 selectArr
// 表格渲染数组 tableRightData

const selectHandler = (val, row) => {
  if (saveArr.value.length != 0) {
    if (!val.some(ele => ele.id == row.id)) {
      saveArr.value = saveArr.value.filter(item => item.id != row.id)
      tableRightData.value = saveArr.value
    }
  }
}

// 全选
const selectAllHandler = val => {
  console.log('全选', val)
  if (val.length == 0) {
    tableData.value.forEach(item => {
      saveArr.value = saveArr.value.filter(ele => ele.id != item.id)
      tableRightData.value = saveArr.value
    })
  }
  // if (saveArr.value.length != 0) {
  //   if (!val.some(ele => ele.id == row.id)) {
  //     saveArr.value = saveArr.value.filter(item => item.id != row.id)
  //     tableRightData.value = saveArr.value
  //   }
  // }
}

// 勾选改变处理函数
const handleSelectionChange = (val: any) => {
  // console.log('勾选的val', val)
  selectArr.value = val
  if (saveArr.value.length == 0) {
    // 如果是第一次即saveArr没存，右边就是勾选数组
    tableRightData.value = val
  } else {
    // 已经切换过，右边表格不能被勾选数组影响，但是对比，勾选有的，遍历没的新增
    val.forEach(objA => {
      // console.log(objA)
      if (!saveArr.value.some(objB => objB.id == objA.id)) saveArr.value.push(objA)
      // saveArr.value = saveArr.value.filter(ele => ele)
    })
    // if(val.length == 0)  {
    //   saveArr.value  = []
    // }
    tableRightData.value = saveArr.value
  }
  // const selectedRows = tableRef.value.getSelectionRows();
}

let saveArr = ref([])

// 保存 处理函数
const saveHandler = () => {
  // console.log('切换前的selectArr', selectArr.value)
  // console.log('切换前saveArr', saveArr.value)
  saveArr.value = saveArr.value.flat()
  // 目标，在切换前，把这一次的选中的数组放进一个saveArr数组保存起来，用push方法，需要去重
  if (saveArr.value.length == 0) {
    saveArr.value.push(selectArr.value)
  } else {
    selectArr.value.forEach(objA => {
      if (!saveArr.value.some(objB => objB.id == objA.id)) saveArr.value.push(selectArr.value)
    })
  }
  saveArr.value = saveArr.value.flat()
  // console.log('处理后的saveArr', saveArr.value)
  tableRightData.value = saveArr.value
}

// 删除处理函数
const deleteHandler = item => {
  console.log('删除序号', item.id)
  if (saveArr.value.length == 0) {
    // 如果是第一次即saveArr没存
    tableRightData.value = tableRightData.value.filter(ele => ele.id != item.id)
    selectArr.value = tableRightData.value.filter(ele => ele.id != item.id)
  } else {
    saveArr.value = saveArr.value.filter(ele => ele.id != item.id)
    tableRightData.value = saveArr.value
    // selectArr.value = tableRightData.value

    tableData.value.forEach(ele => {
      if (ele.id == item.id) {
        tableRef.value.toggleRowSelection(ele, false)
      }
    })
  }
}

// 左边表格实时勾选
const activeHandler = () => {
  // 在点击查询那一瞬间，即表格更新那一瞬间，遍历右边表格数据，确认勾选数组
  if (tableRightData.value.length != 0) {
    console.log('自动勾选', tableRightData.value) //有数据
    // console.log(tableRef.value) //节点获取正确
    tableData.value.forEach(ele => {
      tableRightData.value.forEach(item => {
        if (ele.id == item.id) {
          tableRef.value.toggleRowSelection(ele, true)
        }
        // else {
        //   tableRef.value.toggleRowSelection(ele, false)

        // }
      })
    })
  }
}

let getSotrageList = data => {
  // saveArr.value = tableRightData.value
  // console.log('保存的数组', saveArr.value)
  // if (selectArr.value.length != 0) arr = selectArr.value
  loading.value = true
  http.get(`warehouse/storage`, data).then(r => {
    console.log('仓库数据：', r.data.data)
    tableData.value = r.data.data
    loading.value = false

    // tableRightData.value = saveArr.value
    // if (selectArr.value.length != 0) {
    //   // tableRightData.value =  tableData.value.filter(item=>item.id == selectArr.)
    //   console.log(tableRef.value)
    //   selectArr.value.forEach(item => {
    //     console.log(tableData.value)
    //     let row = tableData.value.find(ele => ele.id == item.id)
    //     console.log(row)
    //     tableRef.value.toggleRowSelection(row, true)
    //   })
    // }
  })
}

// getSotrageList(query)

watch(
  () => props.wmsCode,
  (newValue, oldValue) => {
    if (newValue != oldValue) {
      console.log('监听改变', newValue, oldValue)
      // wmsCode.value = newValue
      query.fnumber = newValue
      getSotrageList(query)
    }
  },
  { immediate: true, deep: true },
)

let emit = defineEmits(['send-data'])

const confirmStorage = () => {
  console.log('仓库数组库位：', tableRightData.value)
  let arr = tableRightData.value.map(ele => ele.warehousecode)
  console.log('仓库数组库位：', arr)
  emit('send-data', arr)
}
const closeHandler = () => {
  ElMessageBox.confirm('还未保存哦，是否需要保存再关闭呢', '保存提示', {
    confirmButtonText: '确认保存',
    cancelButtonText: '取消保存',
    type: 'warning',
  })
    .then(() => {
      let arr = tableRightData.value.map(ele => ele.warehousecode)
      emit('send-data', arr)
    })
    .catch(() => {
      emit('send-data', [])
    })
}

onMounted(() => {})
onUpdated(() => {
  activeHandler()
})
</script>


<style>
.box {
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 100%;
  height: 100%;
  overflow: auto;
}
.el-overlay-dialog {
  overflow: auto;
}
.el-form--inline .el-form-item {
  margin-bottom: 10px;
}
.dialog-view {
  padding: 10px;
  display: flex;
  align-items: flex-start;
  justify-content: space-around;
}
.dialog-view-item {
  overflow: auto;
  height: 100%;
  border: 1px solid #ccc;
}
.dialog-footer {
  padding: 20px;
  text-align: left;
}
.storage-box {
  padding: 10px;
}
</style>

